package com.qualityevaluationclouduser.controller;

import com.alibaba.fastjson.JSONObject;
import com.qualityevaluationclouduser.entity.UserInfo;
import com.qualityevaluationclouduser.service.UserInfoService;
import com.qualityevaluationclouduser.service.impl.EmailService;
import com.qualityevaluationclouduser.untils.AuthMDA;
import com.qualityevaluationclouduser.untils.ResultEntity;
import com.qualityevaluationclouduser.untils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: qualityEvaluationCloudProject
 * @description: 用户信息控制器
 * @author:
 * @create:
 **/
@Data
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户信息控制器")
public class UserController {

    @Autowired
    UserInfoService userInfoService;
    @Autowired
    EmailService emailService;

    @Value("${web.upload.path}")
    String basePath;

    @ApiOperation(value = "根据用户名获取用户", notes = "根据用户名获取用户")
    @PostMapping("/{username}")
//    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public ResultEntity getUserInfo(@PathVariable("username") String username) {
        //参数判读省略
        UserInfo userInfo = userInfoService.findByName(username);
//        FileReadBytes fileReadBytes=new FileReadBytes();
//        byte[] imgBytes=null;
//        if (user.getAvatar()!=null&&!"".equals(user.getAvatar())){
//            imgBytes=fileReadBytes.returnBytes(user.getAvatar());
//        }
//        resUser.put("avatar",imgBytes);
        log.info("这里是---根据用户名获取用户------------------");
        return ResultUtils.build(userInfo);
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation(value = "用户注册", notes = "个人用户注册")
    public ResultEntity register(HttpServletRequest servletRequest) throws IOException {
        MultipartFile file = null;
        if (servletRequest instanceof StandardMultipartHttpServletRequest) {
            MultiValueMap<String, MultipartFile> fileMap = ((StandardMultipartHttpServletRequest) servletRequest)
                    .getMultiFileMap();
            List<MultipartFile> file1 = fileMap.get("file");
            if (null != file1)
                file = file1.get(0);
        }
        JSONObject userJsonObject = (JSONObject) JSONObject.parse(servletRequest.getParameter("user"));
        UserInfo userInfo = JSONObject.toJavaObject(userJsonObject, UserInfo.class);
        Long roleId = Long.parseLong(JSONObject.parse(servletRequest.getParameter("roleId")).toString());
        log.info("这里是---用户注册------------------");
        return ResultUtils.build(userInfoService.register(file, userInfo, roleId));
    }

    @RequestMapping(value = "/editPic", method = RequestMethod.POST)
    @ApiOperation(value = "编辑头像(file:文件，userId:用户id)", notes = "编辑头像")
    public ResultEntity editPic(HttpServletRequest servletRequest) throws IOException {
        MultipartFile file = null;
        if (servletRequest instanceof StandardMultipartHttpServletRequest) {
            MultiValueMap<String, MultipartFile> fileMap = ((StandardMultipartHttpServletRequest) servletRequest)
                    .getMultiFileMap();
            List<MultipartFile> file1 = fileMap.get("file");
            if (null != file1)
                file = file1.get(0);
        }
        Long uid = Long.parseLong(servletRequest.getParameter("userId"));
//        User user = JSONObject.toJavaObject(userJsonObject, User.class);
        log.info("这里是---编辑头像userId------------------");
        return ResultUtils.build(userInfoService.editPicture(file, uid));
    }

    @GetMapping("/list")
    @ApiOperation(value = "用户列表", notes = "用户列表")
//    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public ResultEntity findAllUsers() {
        log.info("这里是---用户列表------------------");
        List<UserInfo> resUser = userInfoService.findAllUserInfos();
        List<UserInfo> resUsers = new ArrayList<>();
        for (UserInfo userInfo : resUser
        ) {
            userInfo.setPassword("");
            resUsers.add(userInfo);
        }

        return ResultUtils.build(resUsers);
    }

    @GetMapping("/page")
    @ApiOperation("用户列表分页查询")
    public ResultEntity pageQueryUserList(@RequestParam int page, @RequestParam int size) {
        log.info("这里是---用户列表分页查询------------------");
        return ResultUtils.build(userInfoService.pageQueryUserInfoList(page, size));
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息")
//    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public ResultEntity update(@RequestBody UserInfo userInfo) {
        log.info("这里是---更新用户信息------------------");
        return ResultUtils.build(userInfoService.modifyUserInfo(userInfo));
    }

    @DeleteMapping("/delete/{userId}")
    @ApiOperation(value = "用户注销", notes = "用户注销")
//    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public void delete(@PathVariable String userId) {
        log.info("这里是---用户注销------------------");
        userInfoService.delUserInfo(userId);
    }

    @PostMapping("/empower")
    @ApiOperation(value = "赋权", notes = "赋权")
    public void empower(@RequestParam("userId") String userId, @RequestParam("roleId") String roleId) {
        log.info("这里是---用户赋权------------------");
        userInfoService.empower(userId, roleId);
    }

    @PostMapping("/reset")
    @ApiOperation(value = "重置密码", notes = "重置密码")
    public boolean resetPassword(@RequestParam String id, @RequestParam String password, @RequestParam String newPassword) {
        log.info("这里是---重置密码------------------");
        return userInfoService.resetPassword(id, password, newPassword);
    }

    @PutMapping("/state")
    @ApiOperation(value = "修改状态", notes = "修改状态")
    public ResultEntity changeState(@RequestParam Long userId) {
        log.info("这里是---修改状态------------------");
        return ResultUtils.build(userInfoService.changeState(userId));
    }

    /**
     * 发送邮件
     *
     * @param jsonObject 邮箱地址
     */
    @ApiOperation(value = "邮箱地址", notes = "邮箱地址")
    @PostMapping("/sendEmail")
    public void senEmailMessage(@RequestBody JSONObject jsonObject) {
        //随机验证码 字母+数字
        String message = AuthMDA.genRandomNum();
        try {
            String loginName = jsonObject.getString("loginName");
            UserInfo userInfo = userInfoService.findByName(loginName);
            //发送邮件
            emailService.senEmailSpring(message, userInfo.getEmail().trim());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("这里是---发送邮件验证码------------------");
    }

    /**
     * 修改密码
     *
     * @param jparms jsonobject必须包含 用户名 ，新密码、验证码
     * @return
     */
    @ApiOperation(value = "jsonobject必须包含 用户名 ，新密码、验证码", notes = "jsonobject必须包含 用户名 ，新密码、验证码")
    @PostMapping("/updatepassword")
    public ResultEntity updatePassword(JSONObject jparms) {
        userInfoService.updatePassword(jparms);
        log.info("这里是---找回密码------------------");
        return ResultUtils.build("修改成功");
    }

    /**
     * 判断验证码是否存在
     *
     * @param jparms 必须包含验证和邮箱地址
     * @return
     */
    @ApiOperation(value = "判断验证码是否存在", notes = "判断验证码是否存在")
    @PostMapping("/isemail")
    public ResultEntity isEmailCode(JSONObject jparms) {
        log.info("这里是---判断验证码是否存在------------------");
        return ResultUtils.build(userInfoService.findEmailCode(jparms));
    }

    @ApiOperation(value = "批量删除(idString形如：id1,id2,id3)", notes = "批量删除(idString形如：id1,id2,id3)")
    @DeleteMapping("/batch")
    public void batchDelete(@RequestParam("idString") String idString) {
        String[] split = idString.split(",");
        List<Long> ids = new ArrayList<>();
        for (String id : split) {
            ids.add(Long.parseLong(id));
        }
        log.info("这里是---用户批量删除------------------");
        userInfoService.deleteUserInfosByIdIn(ids);
    }

    @GetMapping("/specificPage")
    @ApiOperation(value = "根据条件分页查询", notes = "根据条件分页查询")
    public ResultEntity specificPageUserInfo(String username, String gender, String mobile, String identifyCode,String version,String status, @RequestParam int page, @RequestParam int size) {
        return ResultUtils.build(userInfoService.pageQueryByAccountAndGenderAndStatus(username, gender, mobile, identifyCode, version, status, page, size));
    }

    @GetMapping("/getRole")
    @ApiOperation("获取用户角色")
    public ResultEntity queryRoleInfoByUser(Long userId)
    {
        return ResultUtils.build(userInfoService.queryRoleInfoByUser(userId));
    }

    @GetMapping("/getRoleReUserList")
    @ApiOperation("获取用户角色")
    public ResultEntity queryUserListByRole(Long userId,int page,int size)
    {
        return ResultUtils.build(userInfoService.queryUserListByRole(userId,page,size));
    }

    @GetMapping("/getMenuListByUser")
    @ApiOperation("获取用户权限")
    public ResultEntity queryMenuInfoListByUser(Long userId)
    {
        return ResultUtils.build(userInfoService.queryMenuInfoListByUser(userId));
    }

    @GetMapping("/getMenuListByRole")
    @ApiOperation("获取角色权限")
    public ResultEntity queryMenuInfoListByRole(Long roleId)
    {
        return ResultUtils.build(userInfoService.queryMenuInfoListByRole(roleId));
    }
}
